package research.ui.editors.tableeditors.formula;

import research.domain.Component;
import research.domain.ComponentValue;
import research.entity.Entity;
import research.ui.editors.tableeditors.EntityCellModifier;
import research.ui.editors.tableeditors.EntityLabelProvider;

public class FormulaCellModifier extends EntityCellModifier {

	public FormulaCellModifier(FormulaTableEditor viewer) {
		super(viewer);
	}

	@Override
	public boolean canModify(Object element, String property) {
		if (getColumnIndex(property) == 1) {
			ComponentValue par = (ComponentValue) element;
			if (par.isIs_main())
				return false;
		}
		return super.canModify(element, property);
	}

	@Override
	protected Object getValue(Entity entity, int columnIndex) {
		ComponentValue par = (ComponentValue) entity;

		switch (columnIndex) {
		case 0:
			Component component = par.getComponent();
			if (component == null)
				return new Integer(0);
			
            String[] names = ((FormulaTableEditor)viewer).getComponentsNames();
            int i = names.length - 1;
            while (!component.getName().equals(names[i]) && i > 0)
                --i;
            return new Integer(i);
		case 1:
			return EntityLabelProvider.render(par.getPercent());
		case 2:
			return new Boolean(par.isIs_main());
		default:
		}
		return null;
	}

	@Override
	protected void modify(Entity entity, int columnIndex, Object value) {
		ComponentValue par = (ComponentValue) entity;
		switch (columnIndex) {
		case 0:
			par.setComponent(((FormulaTableEditor)viewer).getComponentByNameIdx(((Integer) value).intValue()));
			break;
		case 1:
			par.setPercent(parseDouble(value));
			break;
		case 2:
			boolean isMain = ((Boolean)value).booleanValue();
			par.setIs_main(isMain);
			if (isMain) {
				((FormulaTableEditor) this.viewer).setMain(par);
				par.setPercent(100.0);
			}
			break;
		default:
		}
	}

}
